package ThreadDemo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-10-27
 * Time: 16:12
 */
//模拟实现固定线程数目的线程池
public class MyThreadPool {
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10);

    //指定线程池线程数目
    public MyThreadPool(int n){
        //实例化线程池时应将线程创建好
        for (int i = 0; i < n; i++) {
            Thread thread = new Thread(() -> {
                //线程一旦创建，就应该不停的往队列读取任务并执行
                while(true){
                    try {
                        Runnable task = queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            thread.start();//启动线程
        }
    }

    //往阻塞队列中添加任务
    public void submit(Runnable task) throws InterruptedException {
        queue.put(task);
    }

    public static void main(String[] args) throws InterruptedException{
        MyThreadPool pool = new MyThreadPool(1000);

        //添加任务并执行
        for (int i = 0; i < 100; i++) {
            int id = i;//避免变量捕获
            pool.submit(() -> {
                System.out.println("task " + id + " ---- " + Thread.currentThread().getName());
            });
        }
    }
}
